import java.lang.System;

/**
 * 二分搜索/二分查找
 * 适用场景：数据已经升序排列
 */
public class BinarySearch {

    public int solution(int[] nums, int target) {
        int pivot, left = 0, right = nums.length -1;
        while (left <= right) {
            pivot = left + (right - left) / 2;
            System.out.print("nums[pivot]: " + nums[pivot]);
            if (nums[pivot] == target) return pivot;
            if (target < nums[pivot]) {
                right = pivot -1; // 小数字在大数字的右边
            } else {
                left = pivot +1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{12, 22, 32, 42, 52, 62, 72, 82, 92};
        // int[] nums = new int[]{92, 82, 72, 62, 52, 42, 32, 22, 12};
        int target = 32;
        int result = new BinarySearch().solution(nums, target);
        System.out.print("result: " + result);
    }
}
